package com.hangzhou.xyj.ui.adapter;

import android.app.Dialog;
import android.content.Context;
import android.os.RemoteException;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.CommentModel;
import com.hangzhou.xyj.model.DianDramaModel;
import com.hangzhou.xyj.model.DramaModel;
import com.hangzhou.xyj.model.DynamicDetailModel;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.model.type.EPlayControlType;
import com.hangzhou.xyj.model.type.EUserType;
import com.hangzhou.xyj.net.handler.DeleteCommentHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.net.request.DeleteCommentReq;
import com.hangzhou.xyj.ui.adapter.viewholder.CommentViewHolder;
import com.hangzhou.xyj.ui.dialog.LoadingDialog;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.CommonFollowButton;
import com.hangzhou.xyj.ui.widget.SelectMenuDialog;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.AppConstants;
import com.mediaideas.videoengine.lyrics.LrcView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by neo.duan on 2016/1/18.
 * 戏剧播放Adapter
 */
public class DramaPlayAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public SelectMenuDialog menuDialog;
    /**
     * 戏曲播放
     */
//    public static EPlayControlType PLAY_STATE /*= EPlayControlType.PAUSE*/;
    OnNumChangeListener mNumChangeListener;
    OnRefreshDataListenter onRefreshDataListenter;
    OnSingClickListener onSingClickListener;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private DramaModel mDramaModel;
    private DynamicDetailModel mDetailModel;
    private List<CommentModel> mCommentList;
    private OnPlayStatusChangedListener mListener;
    private boolean isUpdateNum;
    private LoadingDialog mLoadingDialog;
    private int mDramaPos; //当前播放的曲目在list的位置
    private EIntentTagType mIntentTag;
    private boolean mFromUser;//seekBar的拖动 是否来自用户

    public DramaPlayAdapter(Context context) {
        this.mContext = context;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mLoadingDialog = new LoadingDialog(context);
    }

    public void setOnRefreshDataListenter(OnRefreshDataListenter listenter) {
        this.onRefreshDataListenter = listenter;
    }

    public void setIntentTag(EIntentTagType type) {
        this.mIntentTag = type;
    }

    public void setOnSingClickListener(OnSingClickListener listener) {
        this.onSingClickListener = listener;
    }

    /**
     * 更新播放界面
     *
     * @param model
     */
    public void updateDramaInfo(DramaModel model) {
        this.mDramaModel = model;
        notifyDataSetChanged();
    }

//    /**
//     * 初始化播放状态
//     *
//     * @param type
//     */
//    public void initPalyState(EPlayControlType type) {
//        PLAY_STATE = type;
//    }

    /**
     * 更新评论界面
     *
     * @param list
     */
    public void updateCommentList(List<CommentModel> list) {
        if (list == null) {
            this.mCommentList = new ArrayList<>();
        }
        this.mCommentList = list;
        notifyDataSetChanged();
        onRefreshDataListenter.onRefreshData();
    }

    /**
     * 通过动态model去拿，因为有的元素不是人的信息
     *
     * @param model
     */
    public void updatePersonInfo(DynamicDetailModel model) {
        this.mDetailModel = model;
        notifyItemChanged(1);//仅仅刷新 个人信息
        onRefreshDataListenter.onRefreshData();
    }

    /**
     * 更新个人信息上面的数字信息
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/20 15:27
     */
    public void updatePersonInfoNum(DynamicDetailModel model) {
        if (model == null) {
            model = new DynamicDetailModel();
        }
        isUpdateNum = true;
        this.mDetailModel = model;
        notifyItemChanged(1);
        onRefreshDataListenter.onRefreshData();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        RecyclerView.ViewHolder viewHolder;
        switch (viewType) {
            case 0:
                viewHolder = new DramaPlayViewHolder(mLayoutInflater.inflate(R.layout.layout_drama_play_header, viewGroup, false));
                break;
            case 1:
                viewHolder = new PersonalInfoViewHolder(mLayoutInflater.inflate(R.layout.layout_drama_play_personal_info, viewGroup, false));
                break;
            default:
                viewHolder = new CommentViewHolder(mLayoutInflater.inflate(R.layout.layout_drama_play_comment, viewGroup, false));
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//        onFinishCreateViewHolderListener.OnFinishCreateViewHolder();//开始绑定数据
        if (viewHolder == null) {
            return;
        }
        if (!isUpdateNum) {
            if (viewHolder instanceof DramaPlayViewHolder) {
                ((DramaPlayViewHolder) viewHolder).setData(mDramaModel);
            } else if (viewHolder instanceof PersonalInfoViewHolder) {
                ((PersonalInfoViewHolder) viewHolder).setData(mDetailModel);
                ((PersonalInfoViewHolder) viewHolder).mBtnSing.setOnClickListener(new View.OnClickListener() {//点击 “我要唱”
                    @Override
                    public void onClick(View v) {
                        if (mDetailModel != null) {
                            if (XYJApplication.getUserInfo() == null) {//没有登录
                                IntentManager.getInstance().goLoginActivity(mContext);
                                return;
                            }
                            DianDramaModel dramaModel = new DianDramaModel();
                            dramaModel.setId((int) mDetailModel.getId());
                            dramaModel.setName(mDetailModel.getName());
                            dramaModel.setNativeUrl(mDetailModel.getNative_url()); //原唱
                            dramaModel.setAccompanyUrl(mDetailModel.getAccompany_url());//伴奏
                            dramaModel.setLrcUrl(mDetailModel.getLyric_url()); //歌词
                            onSingClickListener.OnSingClick();//回调 暂停播放
                            IntentManager.getInstance().goRecordActivity(mContext, dramaModel);
                        }
                    }
                });
            }

        } else {
            if (viewHolder instanceof PersonalInfoViewHolder)
                ((PersonalInfoViewHolder) viewHolder).setData(mDetailModel);
        }
        if (viewHolder instanceof PersonalInfoViewHolder) {//个人头像
            ((PersonalInfoViewHolder) viewHolder).mCivHeadImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mDetailModel.getUserId() == Integer.valueOf(XYJApplication.getUserInfo().getUserId())) {
                        ToastUtil.show("不能点击自己哦~");
                        return;
                    }
                    IntentManager.getInstance().goExpertInfoActivity(mContext, mDetailModel.getUserId(), mDetailModel.getNickname(),
                            PublicUtil.getUserType(mDetailModel.getType(), mDetailModel.getCheckFlag()));
                }
            });
        }
        if (viewHolder instanceof CommentViewHolder && mCommentList != null) {
            final CommentModel commentModel = mCommentList.get(position - 2);
            ((CommentViewHolder) viewHolder).setData(commentModel);
            //我的评论 添加删除功能
            //如果是我自己的评论
            if (commentModel.getUserId().equals(String.valueOf(CommonPreferences.getUserId(mContext)))) {
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        menuDialog = new SelectMenuDialog(mContext);
                        String[] menu = new String[]{"删除"};
                        menuDialog.setMenu(menu, new SelectMenuDialog.SelectMenuClickListener() {
                            @Override
                            public void onSelectMenuClick(Dialog dialog, View item, int innerPosition) {
                                dialog.dismiss();
                                deleteComment(commentModel.getId(), position - 2, viewHolder.getAdapterPosition());
                            }
                        });
                        menuDialog.show();
                    }
                });
            } else {
                ((CommentViewHolder) viewHolder).mCivHeadImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//跳转个人信息主页
                        IntentManager.getInstance().goExpertInfoActivity(mContext, Integer.valueOf(commentModel.getUserId()),
                                commentModel.getUserName(), PublicUtil.getUserType(commentModel.getType(), commentModel.getCheckFlag()));
                    }
                });
            }
        }
    }

    public void setOnNumChangeListener(OnNumChangeListener listener) {
        this.mNumChangeListener = listener;
    }

    /**
     * 删除评论
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/7 17:01
     */
    public void deleteComment(int commentId, final int position, final int adapterPosition) {
        DeleteCommentReq commentReq = new DeleteCommentReq(commentId);
        HttpLoader.getInstance().sendRequest(new DeleteCommentHandler(commentReq, new HttpResponseListener() {
            @Override
            public void onStart() {
                mLoadingDialog.show();
            }

            @Override
            public void onSuccess(Object model) {
                mLoadingDialog.dismiss();
                //删除成功
                mCommentList.remove(position);
                notifyItemRemoved(adapterPosition);
                //刷新评论数
                mNumChangeListener.onNumchange();
            }

            @Override
            public void onFail(String msg) {
                mLoadingDialog.dismiss();
            }

            @Override
            public void onDone(String msg) {
                mLoadingDialog.dismiss();
            }

            @Override
            public void onError() {
                mLoadingDialog.dismiss();
            }
        }, 0));
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        if (mCommentList == null || mCommentList.size() == 0) {
            return 2;
        } else {
            return mCommentList.size() + 2;
        }
    }

    public void setOnPlayStatusChangedListener(OnPlayStatusChangedListener listener) {
        mListener = listener;
    }

    public interface OnSingClickListener {
        void OnSingClick();//点击了 “我要唱”
    }

    public interface OnRefreshDataListenter {
        void onRefreshData();
    }

    /**
     * 删除评论 取消点赞的时候 刷新动态详情下面的数字，回调接口
     *
     * @param
     * @author yaohuix
     * @return
     * @date 2016/4/8 17:42
     */
    public interface OnNumChangeListener {
        void onNumchange();
    }

    /**
     * 播放状态处理接口
     */
    public interface OnPlayStatusChangedListener {
        void onPlayClick(View view, EPlayControlType type);

        void onProgressChanged(SeekBar seekBar, int progress);

        //上一首
        void onPlayPrevious(View view);

        //下一首
        void onPlayNext(View view) throws RemoteException;
    }

    public class DramaPlayViewHolder extends RecyclerView.ViewHolder {
        public View mItemView;
        public LrcView mLrcView;
        public TextView mTvCurrentTime;
        public TextView mTvTotalTime;
        public SeekBar mSeekBar;
        public ImageView mIvPlay;
        public ImageView mIvPrevious; //上一首
        public ImageView mIvNext; //下一首
//        private DramaModel mModel;

        public DramaPlayViewHolder(View itemView) {
            super(itemView);
            this.mItemView = itemView;
            initView();
        }

        private void initView() {
            mLrcView = (LrcView) mItemView.findViewById(R.id.lrc_view);
            mTvCurrentTime = (TextView) mItemView.findViewById(R.id.tv_play_current_time);
            mTvTotalTime = (TextView) mItemView.findViewById(R.id.tv_play_total_time);
            mIvPrevious = (ImageView) mItemView.findViewById(R.id.iv_drama_play_previous);
            mIvNext = (ImageView) mItemView.findViewById(R.id.iv_drama_play_next);
            mSeekBar = (SeekBar) mItemView.findViewById(R.id.seek_bar_drama_play);
            mIvPlay = (ImageView) mItemView.findViewById(R.id.iv_drama_playing);
            mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    mFromUser = fromUser;
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {//放开拖动条的时候 处理
                    if (mListener != null && mFromUser) {
                        mFromUser = false;
                        mListener.onProgressChanged(seekBar, seekBar.getProgress());
                    }
                }
            });
            mIvPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //改变按钮状态
                    switch (AppConstants.CURRENT_PLAY_STATE) {
                        case PAUSE: //当前为 暂停 状态:播放
                            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PLAY;
                            mIvPlay.setImageResource(R.drawable.ic_drama_pause);
                            break;
                        case PLAY: //当前为 播放 状态:暂停
                            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PAUSE;//
                            mIvPlay.setImageResource(R.drawable.ic_drama_playing);
                            break;
                        case STOP://当前为 停止 状态：播放
                            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.STOP;
                            break;
                        default:
                            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PLAY;
                            break;
                    }
                    if (mListener != null) {
                        mListener.onPlayClick(v, AppConstants.CURRENT_PLAY_STATE);
                    }
                }
            });

            //上一首
            mIvPrevious.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onPlayPrevious(v);
                    }
                }
            });
            //下一首
            mIvNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        try {
                            mListener.onPlayNext(v);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        public void setData(DramaModel model) {
            mIvPlay.setImageResource(R.drawable.ic_drama_pause);
        }
    }

    /**
     * 个人信息
     */
    class PersonalInfoViewHolder extends RecyclerView.ViewHolder {

        CircleImageView mCivHeadImg;//头像
        MyTextView mTvName;//昵称
        MyTextView mTvAuthen;//认证
        MyTextView mTvFansNum;//粉丝数
        MyTextView mTvTime;//时间
        MyTextView mTvLocation;//地点
        MyTextView mTvListenNum;//听数量
        MyTextView mTvTransferNum;//转发数量
        MyTextView mTvCommentNum;//评论数量
        MyTextView mTvLikeNum;//点赞数量
        LinearLayout mLlNoData;//没有评论的时候显示
        private CommonFollowButton mBtnFollow;//关注按钮
        private LinearLayout mLlInfo;//点赞数等信息的横条
        private Button mBtnSing;//“我要唱” 按钮

        public PersonalInfoViewHolder(View itemView) {
            super(itemView);
            mCivHeadImg = (CircleImageView) itemView.findViewById(R.id.civ_header);//头像
            mTvName = (MyTextView) itemView.findViewById(R.id.tv_item_username);//昵称
            mTvAuthen = (MyTextView) itemView.findViewById(R.id.mtv_authen);//认证
            mTvFansNum = (MyTextView) itemView.findViewById(R.id.mtv_fans_num);//粉丝数
            mTvTime = (MyTextView) itemView.findViewById(R.id.tv_item_time);//时间
            mTvLocation = (MyTextView) itemView.findViewById(R.id.mtv_location);//地点
            mTvListenNum = (MyTextView) itemView.findViewById(R.id.mtv_listen);//听数量
            mTvTransferNum = (MyTextView) itemView.findViewById(R.id.mtv_transfer_num);//转发数量
            mTvCommentNum = (MyTextView) itemView.findViewById(R.id.mtv_comment_num);//评论数量
            mTvLikeNum = (MyTextView) itemView.findViewById(R.id.mtv_like_num);//点赞数量
            mBtnFollow = (CommonFollowButton) itemView.findViewById(R.id.btn_drama_play_follow);//点赞数量
            mLlNoData = (LinearLayout) itemView.findViewById(R.id.ll_no_data);//没有评论的时候
            mLlInfo = (LinearLayout) itemView.findViewById(R.id.ll_info);//点赞数等信息的横条
            mBtnSing = (Button) itemView.findViewById(R.id.btn_sing);
        }

        public void setData(DynamicDetailModel data) {
            if (data == null) {
                return;
            }
            if (mIntentTag == EIntentTagType.TAG_STAGE_EXPERT) {//如果是名家作品页面进入，只能赏析
                mLlInfo.setVisibility(View.GONE);
                mTvTime.setVisibility(View.GONE);
                mTvLocation.setVisibility(View.GONE);
                mLlNoData.setVisibility(View.GONE);
                mBtnSing.setVisibility(View.VISIBLE);
                mTvAuthen.setCompoundDrawablesWithIntrinsicBounds(PublicUtil.getAuthenIconDrawable(mContext,
                        EUserType.FAMOUS_EXPERT), null, null, null);
                mTvAuthen.setText("名家");
            } else {
                mTvListenNum.setText(String.valueOf(data.getListenNum()));
                mTvTransferNum.setText(String.valueOf(data.getTransferNum()));
                mTvCommentNum.setText(String.valueOf(data.getCommentNum()));
                mTvLikeNum.setText(String.valueOf(data.getLikeNum()));
                mTvTime.setText(data.getTime());
                mTvLocation.setText(data.getLocation());
                if (mCommentList == null || mCommentList.isEmpty()) {
                    mLlNoData.setVisibility(View.VISIBLE);
                } else {
                    mLlNoData.setVisibility(View.GONE);
                }
                mTvAuthen.setCompoundDrawablesWithIntrinsicBounds(PublicUtil.getAuthenIconDrawable(mContext,
                        PublicUtil.getUserType(data.getType(), data.getCheckFlag())), null, null, null);
                mTvAuthen.setText(PublicUtil.getUserTypeStr(data.getType(), data.getCheckFlag()));
            }
            mCivHeadImg.displayImage(data.getUserHead());
            mTvName.setText(data.getNickname());
            mTvFansNum.setText(String.valueOf(data.getFansNum()));
            mBtnFollow.setFollow(data.isFollow(), data.getUserId()); //是否关注，关注人的id

        }

//        public void updateNumData(DynamicDetailModel data) {
//
//            mCivHeadImg.displayImage(data.getUserHead());
//            mTvName.setText(data.getNickname());
//            mTvFansNum.setText(String.valueOf(data.getFansNum()));
//            mBtnFollow.setFollow(data.isFollow(), data.getUserId()); //是否关注，关注人的id
//
//            mTvListenNum.setText(String.valueOf(data.getListenNum()));
//            mTvTransferNum.setText(String.valueOf(data.getTransferNum()));
//            mTvCommentNum.setText(String.valueOf(data.getCommentNum()));
//            mTvLikeNum.setText(String.valueOf(data.getLikeNum()));
//            if (mCommentList != null && !mCommentList.isEmpty()) {
//                mLlNoData.setVisibility(View.GONE);
//            }
//        }
    }

}
